<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../teacher/js/elementui/index.css">
    <script src="../teacher/js/vue.js"></script>
    <script src="../teacher/js/elementui/index.js"></script>
    <script src="../teacher/js/axios.min.js"></script>
    <script src="/student/js/jquery.js"></script>
    <script src="js/judgePermission.js"></script>
    <style>
        .el-main {
            padding-top: 0;
        }
    </style>
</head>
<body>
<div id="app">
    <el-container>
        <el-main>
            <el-row :gutter="20">
                <el-col :span="4">
                    <div>用户名:</div>
                    <el-input v-model="query.userName" placeholder="请输入用户名"></el-input>
                </el-col>
                <el-col :span="4">
                    <span>邮箱:</span>
                    <el-input v-model="query.protectEMail" placeholder="请输入邮箱"></el-input>
                </el-col>
                <el-col :span="4">
                    <span>手机号:</span>
                    <el-input v-model="query.protectMTel" placeholder="请输入手机号"></el-input>
                </el-col>
                <el-col :span="7">
                    <span>是否锁定:</span>
                    <div>
                        <el-radio v-model="query.isLockout" border label="">全选</el-radio>
                        <el-radio v-model="query.isLockout" border label="是">锁定</el-radio>
                        <el-radio v-model="query.isLockout" border label="否">未锁定</el-radio>
                    </div>
                </el-col>
                <el-col :span="2">
                    <span>&nbsp;</span>
                    <el-button icon="el-icon-refresh" type="primary" @click="search">搜索</el-button>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <span>创建时间:</span>
                    <el-date-picker
                            v-model="query.createTime"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-col>
                <el-col :span="3">
                    <span>排序:</span>
                    <div>
                        <el-select v-model="query.order" placeholder="请选择" clearable>
                            <el-option value="CreateTime" label="创建时间"></el-option>
                            <el-option value="LastLoginTime" label="最后登录时间"></el-option>
                        </el-select>
                    </div>
                </el-col>
                <el-col :span="3">
                    <span>&nbsp;</span>
                    <div>
                        <el-button type="success" @click="templateShow">下载模板</el-button>
                    </div>
                </el-col>
                <el-col :span="2">
                    <span>&nbsp;</span>
                    <div>
                        <el-button permissionValue="user:exports" type="success" @click="exports">导出</el-button>
                    </div>
                </el-col>
                <el-col :span="3">
                    <span>&nbsp;</span>
                    <div permissionValue="user:import">
                        <el-upload class="avatar-uploader" action="/api/admin/user/import"
                                   :show-file-list="false"
                                   :on-success="handSuccess"
                                   :headers="authHead">
                            <el-button type="primary">导入用户</el-button>
                        </el-upload>
                    </div>
                </el-col>
                <el-col :span="3">
                    <span>&nbsp;</span>
                    <div permissionValue="user:add">
                        <el-button type="success" @click="addUserShow">新增用户</el-button>
                    </div>
                </el-col>
                <el-col :span="1">
                    <span>&nbsp;</span>
                    <el-button icon="el-icon-refresh" type="primary" onclick=" window.location.reload();">刷新</el-button>
                </el-col>
            </el-row>
            <el-row style="margin-top: 20px;" permissionValue="user:query">
                <el-table :data="userData" border>
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            prop="loginName"
                            label="用户名"
                            width="70">
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            label="创建时间">
                    </el-table-column>
                    <el-table-column
                            prop="lastLoginTime"
                            label="最后登录时间">
                    </el-table-column>
                    <el-table-column
                            prop="protectEMail"
                            label="邮箱">
                    </el-table-column>
                    <el-table-column
                            prop="protectMTel"
                            label="手机号">
                    </el-table-column>
                    <el-table-column
                            prop="isLockout"
                            label="是否锁定">
                        <template slot-scope="scope">
                            <div>
                                <el-switch
                                        permissionValue="user:updateUserField"
                                        v-model="scope.row.isLockout"
                                        active-value="是"
                                        inactive-value="否"
                                        @change="isLockoutChange(scope.row)"
                                >
                                </el-switch>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="lockTime"
                            label="锁定时间">
                        <template slot-scope="scope">
                            <div v-show="scope.row.isLockout=='是'">
                                {{scope.row.lockTime}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="设置">
                        <template slot-scope="scope">
                            <el-button type="text" permissionValue="user:setRole" @click="showRole(scope.row)">设置角色</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <div>
                                <el-button permissionValue="user:update" type="text" @click="updateUserShow(scope.row)">修改</el-button>
                            </div>
                            <div>
                                <el-button permissionValue="user:delete" type="text" @click="deleteUser(scope.row.id)">删除</el-button>
                            </div>
                            <div permissionValue="user:updateUserField">
                                <el-button type="text" @click="updateUserField('password','',scope.row.id)">重置密码
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
            <el-row type="flex" justify="center">
                <el-pagination
                        layout="prev, pager, next"
                        :current-page.sync="query.page"
                        :page-size="query.rows"
                        @current-change="queryUser"
                        :total="total">
                </el-pagination>
            </el-row>
        </el-main>
    </el-container>
    <div>
        <el-dialog
                title="设置角色"
                :visible.sync="role.show">
            <el-transfer
                    @change="userSetRole"
                    :titles="['未拥有', '已拥有']"
                    v-model="role.values"
                    :data="role.roleAll"></el-transfer>
        </el-dialog>
        <el-dialog
                :title="add.title"
                :visible.sync="add.show">
            <el-form :rules="addRules" ref="addForm" :model="add" label-position="left" label-width="80px">
                <el-form-item prop="loginName" label="用户名称">
                    <el-input v-model="add.loginName" :disabled="add.nameDisabled"></el-input>
                </el-form-item>
                <el-form-item prop="protectEMail" label="邮箱">
                    <el-input v-model="add.protectEMail"></el-input>
                </el-form-item>
                <el-form-item prop="protectMTel" label="手机号">
                    <el-input v-model="add.protectMTel"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-if="add.nameDisabled" @click="updateUser">修改</el-button>
                    <el-button type="primary" v-else @click="addUser">新增</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog
                title="下载模板"
                :visible.sync="template.show">
            <el-checkbox-group v-model="template.checkList">
                <el-checkbox v-for="(item,i) in template.data" :key="i" :label="item.name" :disabled="item.noNull">

                </el-checkbox>
            </el-checkbox-group>
            <div slot="footer">
                <el-button type="success" size="large" long @click="downTemplate">下载</el-button>
            </div>
        </el-dialog>
    </div>
</div>
</body>
<script>
    axios.defaults.headers.common['Authorization'] = "bearer " + sessionStorage.getItem("access_token");
    axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';

    let main = {
        data() {
            return {
                template: {
                    show: false,
                    checkList: [],
                    data: []
                },
                addRules: {
                    loginName: [
                        {required: true, message: '请输入用户名称', trigger: 'blur'},
                    ],

                    protectEMail: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                    ],

                    protectMTel: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                    ],

                },
                add: {
                    nameDisabled: true,
                    title: '',
                    show: false,
                    loginName: '',
                    protectEMail: '',
                    protectMTel: '',
                },
                //用户设置角色
                role: {
                    //弹出框显示
                    show: false,
                    //全部角色
                    roleAll: [],
                    //已拥有角色
                    values: [],
                    //当前弹出的用户id
                    userId: '',
                },
                //用户查询条件封装
                query: {
                    userName: '',
                    protectEMail: '',
                    protectMTel: '',
                    isLockout: '',
                    createTime: '',
                    order: '',
                    page: 1,
                    rows: 10
                },
                //用户数据
                userData: [],
                total: 0,
                //上传文件附加额外请求头参数
                authHead: {
                    Authorization: "bearer " + sessionStorage.getItem("access_token")
                }
            }
        },
        computed: {},
        methods: {
            handSuccess(res) {
                if (res.success) {
                    this.$message({
                        type: 'success',
                        message: '导入用户成功'
                    })
                } else {
                    let m = JSON.parse(res.message);
                    this.$message({
                        type: 'error',
                        message: "导入用户:" + m.loginName + " 致使失败 请检查重新导入"
                    })
                }

            },
            downTemplate() {
                axios({
                    method: 'get',
                    url: '/api/admin/user/expertTemplate',
                    responseType: 'blob',
                    params: {
                        names: this.template.checkList.join(",")
                    }
                }).then((res) => {
                    var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'})
                    var url = window.URL.createObjectURL(blob);
                    var aLink = document.createElement("a");
                    aLink.style.display = "none";
                    aLink.href = url;
                    aLink.setAttribute("download", "用户导入模板.xlsx");
                    document.body.appendChild(aLink);
                    aLink.click();
                    document.body.removeChild(aLink); //下载完成移除元素
                    window.URL.revokeObjectURL(url); //释放掉blob对象
                })

            },
            templateShow() {
                axios({
                    method: 'get',
                    url: '/api/admin/user/getTemplate'
                }).then((res) => {
                    this.template.data = res.data;
                    this.template.checkList = res.data.filter(row => {
                        return row.noNull
                    })

                    this.template.checkList = this.template.checkList.map(row => {
                        return row.name;
                    });

                    this.template.show = true;
                })
            },
            //导出
            exports() {
                axios({
                    method: 'get',
                    url: '/api/admin/user/exports',
                    responseType: 'blob',
                    params: {
                        userName: this.query.userName,
                        beginCreateTime: this.date_string(this.query.createTime[0]),
                        endCreateTime: this.date_string(this.query.createTime[1]),
                        isLockout: this.query.isLockout,
                        order: this.query.order,
                        protectEMail: this.query.protectEMail,
                        protectMTel: this.query.protectMTel,
                        page: this.query.page,
                        rows: this.query.rows,
                    }
                }).then(res => {
                    var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'})
                    var url = window.URL.createObjectURL(blob);
                    var aLink = document.createElement("a");
                    aLink.style.display = "none";
                    aLink.href = url;
                    aLink.setAttribute("download", "用户.xlsx");
                    document.body.appendChild(aLink);
                    aLink.click();
                    document.body.removeChild(aLink); //下载完成移除元素
                    window.URL.revokeObjectURL(url); //释放掉blob对象

                })
            },
            //修改用户
            updateUser() {
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        axios({
                            method: 'put',
                            url: '/api/admin/user',
                            data: {
                                loginName: this.add.loginName,
                                protectEMail: this.add.protectEMail,
                                protectMTel: this.add.protectMTel
                            },
                        }).then(res => {
                            res = res.data;
                            if (res.success) {
                                this.queryUser();
                                this.add.show = false;
                                this.$refs['addForm'].resetFields();
                            }
                        })
                    } else {
                        this.$message({
                            showClose: true,
                            message: '新增失败',
                            type: 'error'
                        });
                        return false;
                    }
                });
            },
            //修改用户框显示
            updateUserShow(row) {
                this.add.loginName = row.loginName;
                this.add.protectEMail = row.protectEMail;
                this.add.protectMTel = row.protectMTel;
                this.add.nameDisabled = true;
                this.add.title = "修改用户";
                this.add.show = true;
            },
            //删除用户
            deleteUser(id) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    cancelButtonText: '取消',
                    confirmButtonText: '确定',
                    type: 'warning'
                }).then(() => {
                    axios({
                        method: "delete",
                        url: '/api/admin/user/' + id
                    })
                        .then(res => {
                            res = res.data;
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.queryUser();
                        })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //新增用户
            addUser() {
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        axios({
                            method: 'post',
                            url: '/api/admin/user',
                            data: {
                                loginName: this.add.loginName,
                                protectEMail: this.add.protectEMail,
                                protectMTel: this.add.protectMTel
                            },
                        }).then(res => {
                            res = res.data;
                            if (res.success) {
                                this.queryUser();
                                this.add.show = false;
                                this.$refs['addForm'].resetFields();
                            }
                        })
                    } else {
                        this.$message({
                            showClose: true,
                            message: '新增失败',
                            type: 'error'
                        });
                        return false;
                    }
                });
            },
            //新增用户框显示
            addUserShow() {
                this.add.loginName = "";
                this.add.protectEMail = "";
                this.add.protectMTel = "";
                this.add.nameDisabled = false;
                this.add.title = "新增用户";
                this.add.show = true;
            },
            //给用户设置角色
            userSetRole(value, direction, keys) {
                console.log(value, direction, keys);
                let params = new URLSearchParams();
                params.append("roleIds", keys);
                params.append("direction", direction);
                axios({
                    method: "post",
                    url: '/api/admin/user/setRole/' + this.role.userId,
                    data: params
                }).then(res => {
                    res = res.data;
                    if (res.success) {
                        this.$message({
                            showClose: true,
                            message: '设置成功'
                        });
                    }
                })
            },
            //显示设置角色框
            showRole(row) {
                axios({
                    method: "get",
                    url: '/api/admin/role/getRole/' + row.id,
                }).then(res => {
                    res = res.data;
                    this.role.userId = row.id;
                    this.role.roleAll = res.message.roles;
                    this.role.values = res.message.userRole.map(item => {
                        return item.key;
                    });
                    this.role.show = true
                })
            },
            isLockoutChange(row) {
                this.updateUserField('isLockout', row.isLockout, row.id);
            },
            updateUserField(fieldName, fieldValue, id) {
                let params = new URLSearchParams();
                params.append("fieldName", fieldName);
                params.append("fieldValue", fieldValue);
                axios.put('/api/admin/user/updateUserField/' + id, params)
                    .then(res => {
                        res = res.data;
                        if (res.success) {
                            this.$message({
                                showClose: true,
                                message: '成功'
                            });
                        } else {
                            this.$message({
                                showClose: true,
                                message: '失败',
                                type: 'error'
                            });
                        }
                    })
            },
            search() {
                this.query.page = 1;
                this.queryUser();
            },
            //刷新页面
            reloadHTML() {
                window.location.reload();
            },
            //查询用户
            queryUser() {
                axios({
                    method: 'get',
                    url: "/api/admin/user/query",
                    params: {
                        userName: this.query.userName,
                        beginCreateTime: this.date_string(this.query.createTime[0]),
                        endCreateTime: this.date_string(this.query.createTime[1]),
                        isLockout: this.query.isLockout,
                        order: this.query.order,
                        protectEMail: this.query.protectEMail,
                        protectMTel: this.query.protectMTel,
                        page: this.query.page,
                        rows: this.query.rows,
                    }
                }).then(res => {
                    res = res.data;
                    this.total = res.total;
                    this.userData = res.rows;
                   window.setTimeout(()=>{
                       permissionshow();
                   },1)
                })
            },
            //日期封装
            date_string(date) {
                if (typeof(date) != "object") {
                    return null;
                }
                if (date == "") {
                    return null;
                }
                let year = date.getFullYear();
                let month = (date.getMonth() + 1).toString();
                let day = (date.getDate()).toString();
                let hour = date.getHours();
                let min = date.getMinutes();
                let secod = date.getSeconds();
                if (month.length == 1) {
                    month = "0" + month;
                }
                if (day.length == 1) {
                    day = "0" + day;
                }
                var dateTime = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + secod
                return dateTime;
            }
        },
        mounted() {
            this.queryUser();
        }
    };
    let Component = Vue.extend(main);
    new Component().$mount('#app')
</script>
</html>